package org.example.springboot.task;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.example.springboot.component.SseEmitterServer;
import org.example.springboot.entity.*;
import org.example.springboot.service.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class moistureCheckHandler {

    @Resource
    private IrrigationUnitService irrigationUnitService;

    @Resource
    private FmcMetricsService fmcMetricsService;

    @Resource
    private MoistureControlService moistureControlService;

    @Resource
    private FmcControlService fmcControlService;

    @Resource
    private FmcDataService fmcDataService;

    @Resource
    private SseEmitterServer sseEmitterServer;

    @Resource
    private PendingTasksService pendingTasksService;

    @XxlJob("moistureCheckHandler")
    public void moistureCheck(){
        //查询所有灌溉方式是水分灌溉的单元
        List<IrrigationUnit> irrigationUnitList = irrigationUnitService.list(new QueryWrapper<IrrigationUnit>().eq("type", "03"));
        for (IrrigationUnit irrigationUnit : irrigationUnitList) {
            MoistureControl moistureControl = moistureControlService.getOne(new QueryWrapper<MoistureControl>().eq("irrigation_unit_uuid", irrigationUnit.getUuid()));
            log.info("水分控制信息:{}" , moistureControl);
            String controlDevice = irrigationUnit.getControlDevice();
            FmcMetrics fmcMetrics = fmcMetricsService.getOne(new QueryWrapper<FmcMetrics>().eq("did", controlDevice));
            log.info("当前地块指标：{}", fmcMetrics);

            FmcControl fmcControl = new FmcControl();
            fmcControl.setDid(controlDevice);
            fmcControl.setUnitCode(irrigationUnit.getUnitCode());
            fmcControl.setOperationTime(new Date());
            fmcControl.setTopic("FMC_control/" + controlDevice);
            JSONObject message = new JSONObject();
            message.put("project", "FMC_irrigator");
            message.put("device", controlDevice);

            if (fmcMetrics.getSoilMoisture() <= moistureControl.getVolumeLower()) {
                log.info("土壤水分已达下限，执行灌溉");
                fmcControl.setValt(1);
                message.put("method", "0");
                message.put("valt1", "1");
                //（水分上限-水分下限）*H*A/100
                float volumeUpper = moistureControl.getVolumeUpper() == null ? 0.0f : moistureControl.getVolumeUpper();
                float volumeLower = moistureControl.getVolumeLower() == null ? 0.0f : moistureControl.getVolumeLower();
                float depth = moistureControl.getDepth() == null ? 0.0f : moistureControl.getDepth();
                float area = irrigationUnit.getArea() == null ? 0.0f : irrigationUnit.getArea();
                if (irrigationUnit.getUnit().equals("01")) {
                    area = area * 666.67f;
                }
                float amount = (volumeUpper - volumeLower) * depth * area / 100;
                message.put("amount", String.format("%.3f", amount));
                fmcControl.setMessage(message);
                log.info("开始执行水分灌溉，MQTT消息：{}", message);
                PendingTasks pendingTasks = new PendingTasks();
                pendingTasks.setSort(Integer.valueOf(irrigationUnit.getSym()));
                pendingTasks.setMqttContent(JSONObject.toJSONString(fmcControl));
                pendingTasksService.save(pendingTasks);
               // fmcControlService.sendMessageToMqtt(fmcControl);
                DecimalFormat df = new DecimalFormat("#.000");
                String irrigationVolume = df.format(amount);
                moistureControl.setIrrigationVolume(Float.valueOf(irrigationVolume));
                moistureControlService.updateById(moistureControl);



            }
            sseEmitterServer.broadcast("Refresh");
        }
    }

}
